<template>
  <div class="login_box">
    <el-form ref="form" :model="form" :rules="loginFormRules" class="login_form" label-width="80px">
      <el-form-item label-width="0" prop="username">
        <el-input v-model="form.username" prefix-icon="el-icon-user-solid"></el-input>
      </el-form-item>
      <el-form-item label-width="0" prop="password">
        <el-input show-password v-model="form.password" prefix-icon="el-icon-unlock"></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" @click="onSubmit" :loading="loginLoading">登录</el-button>
        <el-button @click="resetLoginForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        loginLoading: false, // 登录限制
        form: {
          username: 'admin',
          password: '123456'
        },
        loginFormRules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 15,
              message: '长度在 6 到 15 个字符',
              trigger: 'blur'
            }
          ]
        }
      }
    },
    methods: {
      onSubmit() {
        this.loginLoading = true
        this.$refs.form.validate(async valid => {
          if (!valid) {
            return (this.loginLoading = false)
          }
          const {
            data: res
          } = await this.$axios.post('/login', this.form)
          console.log(res)
          console.log(res.code)
          if (res.code != 200) {
            this.loginLoading = false
            return this.$message.error('登录失败 帐号或密码错误!')
          }
          this.$message.success('登录成功!')
          window.sessionStorage.setItem('token', res.result.apikey)
          this.$router.push('/home')
          this.loginLoading = false
        })
      },
      resetLoginForm() {
        console.log('---')
        this.$refs.form.resetFields()
      },
    }
  }
</script>

<style scoped="scoped">
  .login_box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    height: 300px;
    border: #42B983 solid 1px;
  }

  .login_form {
    box-sizing: border-box;
    position: relative;
    top: 25%;
    padding: 0 20px;
  }

  .btns {
    display: flex;
    justify-content: flex-end;
  }
</style>
